<template>
    <div class="micro-server-page">
        <a-spin v-show="loading" :spinning="loading" class="spin-wrapper" size="large" />
        <Transition>
            <micro-app
                v-if="!changing"
                :name="childName"
                :url="url"
                inline
                disable-sandbox
                destory
                :data="containerData"
                class="micro-app-wrapper"
                @created='created'
                @mounted="microMounted"
                @unmount="microUnmount"
                @error="microError"
                @datachange="handleDataChange"
            />
        </Transition>
    </div>
</template>

<script lang="ts" setup>
    import { ref, watch, onMounted, nextTick  } from 'vue'
    import { useRoute } from 'vue-router'
    import { EventCenterForMicroApp } from '@micro-zoe/micro-app'
    import { localGet } from '@/utils/common'
    import { useUserStore } from '@/store/modules/user'
    import { isNullOrUnDef, isArray, isEmpty } from '@/utils/is'
    import { LAYOUT_PLAN_KEY } from '@/constant'
    const userStore = useUserStore()

    const childName = ref('')
    const url = ref('')
    const loading = ref(true)
    const changing = ref(false)
    const route = useRoute()
    const containerData = ref({
        type: 'asa',
        baseroute: '',
        userInfo: { userItem: localGet('al__USER_INFO') }, // 这是将基座的登录信息传给Vite子应用进行免登陆
        url: url.value
    })
    const childPathname = ref('')
    watch(
        () => [route, userStore.currentDepartment],
        () => {
            changing.value = true
            let departmentId = userStore.currentDepartment
            if (departmentId && !isNullOrUnDef(departmentId) && !isArray(departmentId)) {
                departmentId = [departmentId]
            }
          const queryArray: string[] = []
          Object.keys(route.query).forEach(key => {
            queryArray.push(`${key}=${route.query[key]}`)
          })
          let { origin, pathname } = location
          if (pathname.indexOf(LAYOUT_PLAN_KEY) > -1) {
            pathname = pathname.split(LAYOUT_PLAN_KEY)[0]
          }
          if (pathname.indexOf('/adv/') > -1) {
            // 大屏分为了两段 形如 /adv/code
            const [, appBaseRoute, microBaseRoute, adv, childPackageName] = pathname.split('/')
            // 给子应用传递的前缀，vite作为子应用时，由于沙箱需要关闭，所以子应用的路由需要加上前缀才能正确解析1
            containerData.value.baseroute = `/${appBaseRoute}/${microBaseRoute}`
            childName.value = adv + '_' + childPackageName
            let finalUrl = `${origin}/${adv}/${childPackageName}/`;
            // 这里url传参只放在containerData的url里面，因为参数过长，会造成414的问题
            const baseUrl = finalUrl;
            departmentId && !isEmpty(departmentId) && (finalUrl = `${finalUrl}?departmentId=${JSON.stringify(departmentId)}`)
            // 加入连接中的查询参数
            queryArray && queryArray.length > 0 && (finalUrl = `${finalUrl}${finalUrl.indexOf('?') > 0 ? '&' + queryArray.join('&') : '?' + queryArray.join('&')}`)
            // 传递给子应用
            containerData.value.url = finalUrl
            url.value = baseUrl
          } else {
            const [, appBaseRoute, microBaseRoute, childPackageName] = pathname.split('/')
            // 给子应用传递的前缀，vite作为子应用时，由于沙箱需要关闭，所以子应用的路由需要加上前缀才能正确解析1
            containerData.value.baseroute = `/${appBaseRoute}/${microBaseRoute}`
            childName.value = childPackageName
            let finalUrl = `${origin}/${childPackageName}/`
            departmentId && !isEmpty(departmentId) && (finalUrl = `${finalUrl}?departmentId=${JSON.stringify(departmentId)}`)
            // 加入连接中的查询参数
            queryArray && queryArray.length > 0 && (finalUrl = `${finalUrl}${finalUrl.indexOf('?') > 0 ? '&' + queryArray.join('&') : '?' + queryArray.join('&')}`)
            // 传递给子应用
            containerData.value.url = finalUrl
            url.value = finalUrl
          }

          if(childPathname.value !== '' && childPathname.value !== location.pathname) {
              // 切换路由时，reload页面，临时解决切换路由时不渲染的问题
            window.location.reload()
          }

          nextTick(() => {
              changing.value= false
          })
        },
        {
            immediate: true,
            deep: true
        }
    )

    onMounted(() => {
        // 子应用是vite构建的，基座和子应用通信通过下面定义的属性进行
        window.eventCenterForViteApp = new EventCenterForMicroApp(childName.value)
    })

    // 子应用渲染完
    const created = () => {
        // do nothing
        if (childPathname.value !== location.pathname) {
            if (childPathname.value) {
                // 手动触发一下子应用路由
                window.history.pushState(null, '', location.pathname)
                window.dispatchEvent(new PopStateEvent('popstate', { state: null }))
            }
            childPathname.value = location.pathname
        }
    }
    // 子应用渲染完
    const microMounted = () => {
        loading.value = false
    }
    // 子应用卸载
    const microUnmount = () => {
        loading.value = true
    }
    // 子应用渲染出错
    const microError = () => {
        loading.value = false
    }
    // 监听子应用发送来的数据
    const handleDataChange = data => {}
</script>

<style lang="less" scoped>
    .micro-server-page {
        width: 100%;
        height: 100%;
        overflow: hidden;
        position: relative;
        .spin-wrapper {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .micro-app-wrapper,
        .micro-app-wrapper > div {
            height: 100%;
            :deep(micro-app-body) {
              height: 100%;
              overflow-y: auto;
              overflow-x: hidden;
            }
            // 可视化大屏的要屏蔽自定义样式
            .data-visualization-wrapper {
                .view-bg,
                .application-list-header {
                    display: none;
                }
                .@{ant-prefix}-menu-submenu,
                .@{ant-prefix}-menu-item {
                    margin: 4px 0 !important;
                    vertical-align: middle;
                    .al-icon {
                        display: inline-block;
                        width: 18px;
                        height: 18px;
                    }
                }
                .@{ant-prefix}-layout-sider-dark {
                    display: none;
                }
                .menu-title {
                    display: flex;
                    align-items: center;
                }
                .al-data-governance-body {
                    .main {
                        padding-left: 0 !important;
                        .@{ant-prefix}-breadcrumb {
                            display: none;
                        }
                    }
                }
            }
        }
    }
    .v-enter-active,
    .v-leave-active {
        transition: opacity 0.5s ease;
    }

    .v-enter-from,
    .v-leave-to {
        opacity: 0;
    }
</style>
